package com.ruoyi.web.controller.system;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.exception.CustomException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.system.domain.AsyncDetail;
import com.ruoyi.system.domain.DevicePointCheckConfig;
import com.ruoyi.system.domain.ValidationGroups.Create;
import com.ruoyi.system.domain.ValidationGroups.Select;
import com.ruoyi.system.domain.ValidationGroups.Update;
import com.ruoyi.system.domain.vo.PointCheckDeviceDetailVO;
import com.ruoyi.system.domain.vo.QueryVo;
import com.ruoyi.system.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotNull;
import java.util.*;

@Slf4j
@RestController
@RequestMapping("/system/device/point/check/config")
public class DevicePointCheckConfigController extends BaseController {
    @Autowired
    private IDevicePointCheckConfigService devicePointCheckConfigService;
    @Autowired
    private ISysDeptService sysDeptService;

    @Autowired
    private AsyncService asyncService;

    @Autowired
    private IAsyncDetailService asyncDetailService;

    @Autowired
    private IPointCheckDeviceDetailService pointCheckDeviceDetailService;

    @PreAuthorize("@ss.hasPermi('system:product:point:check:config:list')")
    @GetMapping("/list")
    public TableDataInfo queryList(@Validated(Select.class) DevicePointCheckConfig devicePointCheckConfig) {
        QueryVo queryVo = new QueryVo();
        queryVo.filters.put("category", devicePointCheckConfig.getCategory());
        queryVo.filters.put("type", devicePointCheckConfig.getType());
        queryVo.filters.put("device_id", devicePointCheckConfig.getDeviceId());
        if(devicePointCheckConfig.getCategory()==0){
            queryVo.filters.put("field", "运行数值");
        }else{
            queryVo.filters.put("field", devicePointCheckConfig.getField());
        }

        queryVo.filters.put("item", devicePointCheckConfig.getItem());
        queryVo.filters.put("data_type", devicePointCheckConfig.getDataType());
        LoginUser loginUser = SecurityUtils.getLoginUser();
        // 设置companyId
        Long companyId = sysDeptService.selectCompanyIdByUser(loginUser.getUser());
        queryVo.filters.put("company_id", companyId);
        startPage();
        List<DevicePointCheckConfig> devicePointCheckConfigs = devicePointCheckConfigService.queryList(queryVo);
        return getDataTable(devicePointCheckConfigs);
    }

    @PreAuthorize("@ss.hasPermi('system:product:point:check:config:getInfo')")
    @GetMapping("/get_info")
    public AjaxResult getInfo(Integer id) {
        QueryVo queryVo = new QueryVo();
        queryVo.filters.put("id", id);
        DevicePointCheckConfig devicePointCheckConfig = devicePointCheckConfigService.getOne(queryVo);
        return AjaxResult.success(devicePointCheckConfig);
    }

    @PreAuthorize("@ss.hasPermi('system:product:point:check:config:add')")
    @Log(title = "产品自定义点检配置", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @Transactional
    public AjaxResult add(@RequestBody @Validated(Create.class) DevicePointCheckConfig devicePointCheckConfig) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        // 设置companyId
        Long companyId = sysDeptService.selectCompanyIdByUser(loginUser.getUser());
        devicePointCheckConfig.setCompanyId(companyId);
        devicePointCheckConfig.setCreateBy(loginUser.getUsername());
        devicePointCheckConfig.setCreateTime(new Date());
        if(devicePointCheckConfig.getCategory()==0){
            devicePointCheckConfigService.checkIsItem(devicePointCheckConfig);
        }else{
            devicePointCheckConfigService.checkIsExist(devicePointCheckConfig);
        }

        if (devicePointCheckConfigService.add(devicePointCheckConfig)) {
            return AjaxResult.success("添加成功");
        }
        return AjaxResult.error("添加失败");
    }

    @PreAuthorize("@ss.hasPermi('system:product:point:check:config:add')")
    @GetMapping("/init")
    @Transactional
    public AjaxResult init(Integer id) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        // 设置companyId
        Long companyId = sysDeptService.selectCompanyIdByUser(loginUser.getUser());
        if (devicePointCheckConfigService.init(id,companyId,loginUser.getUsername())) {
            return AjaxResult.success("重置成功");
        }
        return AjaxResult.error("重置失败");
    }


    @PreAuthorize("@ss.hasPermi('system:product:point:check:config:edit')")
    @Log(title = "产品自定义点检配置", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    public AjaxResult edit(@RequestBody @Validated(Update.class) DevicePointCheckConfig devicePointCheckConfig) {
        devicePointCheckConfigService.checkIsExist(devicePointCheckConfig);
        if (devicePointCheckConfigService.update(devicePointCheckConfig)) {
            return AjaxResult.success("修改成功");
        }
        return AjaxResult.error("修改失败");
    }

    @PreAuthorize("@ss.hasPermi('system:product:point:check:config:edit')")
    @Log(title = "产品自定义点检配置", businessType = BusinessType.UPDATE)
    @PostMapping("/edit_sys")
    public AjaxResult editSys(@RequestBody @Validated(Update.class) DevicePointCheckConfig devicePointCheckConfig) {

        QueryVo vo = new QueryVo();
        vo.filters.put("id", devicePointCheckConfig.getId());
        DevicePointCheckConfig one = devicePointCheckConfigService.getOne(vo);
        if(one==null){
            return AjaxResult.error("修改失败");
        }
        if(!(devicePointCheckConfig.getItem().equals(one.getItem()))){
            devicePointCheckConfigService.checkIsItem(devicePointCheckConfig);
        }

        QueryVo queryVo = new QueryVo();
        queryVo.filters.put("deviceId", one.getDeviceId());
        queryVo.filters.put("type", one.getType());
        queryVo.filters.put("item", one.getItem());
        queryVo.filters.put("updateItem", devicePointCheckConfig.getItem());
        queryVo.filters.put("typeOrder", devicePointCheckConfig.getTypeOrder());
        queryVo.filters.put("itemOrder", devicePointCheckConfig.getItemOrder());
        queryVo.filters.put("orderNum", devicePointCheckConfig.getOrderNum());

        if (devicePointCheckConfigService.updateSys(queryVo)) {
            return AjaxResult.success("修改成功");
        }
        return AjaxResult.error("修改失败");
    }

    @PreAuthorize("@ss.hasPermi('system:product:point:check:config:delete')")
    @Log(title = "产品自定义点检配置", businessType = BusinessType.DELETE)
    @DeleteMapping("/{id}")
    public AjaxResult delete(@PathVariable @NotNull(message = "id不能为null") Integer id) {
        QueryVo queryVo = new QueryVo();
        queryVo.filters.put("id", id);
        if (devicePointCheckConfigService.delete(queryVo)) {
            return AjaxResult.success("删除成功");
        }
        return AjaxResult.error("删除失败");
    }

    @PreAuthorize("@ss.hasPermi('system:product:point:check:config:delete')")
    @Log(title = "产品自定义点检配置", businessType = BusinessType.DELETE)
    @DeleteMapping("sys/{id}")
    public AjaxResult deleteSys(@PathVariable @NotNull(message = "id不能为null") Integer id) {
        QueryVo queryVo = new QueryVo();
        queryVo.filters.put("id", id);
        DevicePointCheckConfig devicePointCheckConfig = devicePointCheckConfigService.getOne(queryVo);
        QueryVo queryVo1 = new QueryVo();
        queryVo1.filters.put("type",devicePointCheckConfig.getType());
        queryVo1.filters.put("item",devicePointCheckConfig.getItem());
        queryVo1.filters.put("deviceId",devicePointCheckConfig.getDeviceId());

        if (devicePointCheckConfigService.deleteSys(queryVo1)) {
            return AjaxResult.success("删除成功");
        }
        return AjaxResult.error("删除失败");
    }

    @PreAuthorize("@ss.hasPermi('system:product:point:check:config:delete')")
    @DeleteMapping("/delete_batch")
    public AjaxResult deleteBatch(String ids) {
        if (StrUtil.isBlank(ids)) {
            throw new CustomException("配置id不能为空");
        }
        if (devicePointCheckConfigService.deleteBatch(StrUtil.splitTrim(ids, ","))) {
            return AjaxResult.success("删除成功");
        }
        return AjaxResult.error("删除失败");
    }

    @PreAuthorize("@ss.hasPermi('system:product:point:check:config:list')")
    @GetMapping("/enum/{deviceId}")
    public AjaxResult typeItemEnum(@PathVariable @NotNull(message = "产品id不能为null") Integer deviceId) {
        QueryVo queryVo = new QueryVo();
        queryVo.filters.put("device_id", deviceId);
        LoginUser loginUser = SecurityUtils.getLoginUser();
        // 设置companyId
        Long companyId = sysDeptService.selectCompanyIdByUser(loginUser.getUser());
        queryVo.filters.put("company_id", companyId);
        List<Map<String, Object>> typeEnum = devicePointCheckConfigService.typeItemEnum(queryVo);
        return AjaxResult.success(typeEnum);
    }

    @PreAuthorize("@ss.hasPermi('system:product:point:check:config:list')")
    @GetMapping("/enum_check/{deviceId}")
    public AjaxResult typeItemEnumCheck(@PathVariable @NotNull(message = "产品id不能为null") Integer deviceId) {
        QueryVo queryVo = new QueryVo();
        queryVo.filters.put("device_id", deviceId);
        LoginUser loginUser = SecurityUtils.getLoginUser();
        // 设置companyId
        Long companyId = sysDeptService.selectCompanyIdByUser(loginUser.getUser());
        queryVo.filters.put("company_id", companyId);
        List<Map<String, Object>> typeEnum = devicePointCheckConfigService.typeItemEnumCheck(queryVo);
        return AjaxResult.success(typeEnum);
    }

    @PreAuthorize("@ss.hasPermi('system:product:point:check:config:list')")
    @GetMapping("/enum_check_v2/{deviceIds}")
    public AjaxResult typeItemEnumCheckV2(@PathVariable @NotNull(message = "产品id不能为null") String deviceIds) {
        HashMap<String, List> enumMap = new HashMap<>();
        String[]deviceIdArr = deviceIds.split(",");
        for (String deviceId:deviceIdArr
             ) {
            QueryVo queryVo = new QueryVo();
            queryVo.filters.put("device_id", Integer.parseInt(deviceId));
            LoginUser loginUser = SecurityUtils.getLoginUser();
            // 设置companyId
            Long companyId = sysDeptService.selectCompanyIdByUser(loginUser.getUser());
            queryVo.filters.put("company_id", companyId);
            List<Map<String, Object>> typeEnum = devicePointCheckConfigService.typeItemEnumCheck(queryVo);
            if(typeEnum!=null){
                enumMap.put(deviceId,typeEnum);
            }

        }

        return AjaxResult.success(enumMap);
    }

    /**
     * 查询点检类别、点检项枚举，
     *
     * @param deviceId
     * @return
     */
    @PreAuthorize("@ss.hasPermi('system:product:point:check:config:list')")
    @GetMapping("/default/enum/{deviceId}")
    public AjaxResult typeItemPcDefaultEnum(@PathVariable @NotNull(message = "产品id不能为null") Integer deviceId,Date startTime) {
        QueryVo queryVo = new QueryVo();
        queryVo.filters.put("device_id", deviceId);
        LoginUser loginUser = SecurityUtils.getLoginUser();
        // 设置companyId
        Long companyId = sysDeptService.selectCompanyIdByUser(loginUser.getUser());
        queryVo.filters.put("company_id", companyId);
        queryVo.filters.put("start_time", startTime);
        List<Map<String, Object>> typeEnum = devicePointCheckConfigService.typeItemDefaultEnum(queryVo);
        return AjaxResult.success(typeEnum);
    }

    /**
     * 查询点检类别、点检项枚举，
     *
     * @param taskDeviceId
     * @return
     */
    @PreAuthorize("@ss.hasPermi('system:product:point:check:config:list')")
    @GetMapping("/default/enum_v2")
    public AjaxResult typeItemPcDefaultEnumV2(Integer taskDeviceId) {
        List<Map<String, Object>> deviceDetailVO = pointCheckDeviceDetailService.getDeviceDetailVOV2(taskDeviceId);
        return AjaxResult.success(deviceDetailVO);
    }

    @PreAuthorize("@ss.hasPermi('system:product:point:check:config:add')")
    @PostMapping(value = "/{deviceId}/import", produces = "application/json;charset=UTF-8")
    @Log(title = "产品点检配置导入", businessType = BusinessType.INSERT)
    public AjaxResult inject(@PathVariable @NotNull(message = "产品id不能为null") Integer deviceId, @RequestBody JSONObject request) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        Long companyId = sysDeptService.selectCompanyIdByUser(loginUser.getUser());
        String filename = request.getString("filename");
        String tid = asyncDetailService.createTid("导入产品点检配置", companyId);
        asyncService.injectDevicesPointCheckConfig(tid, filename, loginUser.getUsername(), companyId, deviceId);
        return AjaxResult.success(tid);
    }

    @PreAuthorize("@ss.hasPermi('system:product:point:check:config:add')")
    @PostMapping(value = "/import_result", produces = "application/json;charset=UTF-8")
    public AjaxResult injectResult(@RequestBody JSONObject request) {
        String tid = request.getString("tid");
        QueryVo queryVo = new QueryVo();
        queryVo.filters.put("tid", tid);
        AsyncDetail asyncDetail = asyncDetailService.retrieve(queryVo);
        JSONObject result = new JSONObject();
        Integer status = asyncDetail.getStatus();
        result.put("status", status);
        if (status > 0) {
            String output = asyncDetail.getData();
            try {
                result.put("output", JSON.parse(output));
            } catch (Exception e) {
                result.put("output", output);
            }
        }
        return AjaxResult.success(result);
    }




//    @GetMapping("/saveBatch")
//    public AjaxResult saveBatch(Integer deviceId){
//        LoginUser loginUser = SecurityUtils.getLoginUser();
//        Long companyId = sysDeptService.selectCompanyIdByUser(loginUser.getUser());
//        QueryVo queryVo = new QueryVo();
//        queryVo.filters.put("device_id",deviceId);
//        queryVo.filters.put("user_name",loginUser.getUsername());
//        queryVo.filters.put("company_id",companyId);
//        int n = devicePointCheckConfigService.initPointCheckConfigByDeviceId(queryVo);
//        return AjaxResult.success(String.format("共添加了%s",n));
//    }
}
